package com.leo.erp.service.impl;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.LogMapper;
import com.leo.erp.dto.LogExecution;
import com.leo.erp.entity.Log;
import com.leo.erp.entity.User;
import com.leo.erp.enums.LogStateEnum;
import com.leo.erp.service.LogService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.Tools;

@Service
public class LogServiceImpl implements LogService{
	@Autowired
	private LogMapper logMapper;
	
	/**
     * 获取用户id
     * @param request
     * @return
     */
    public int getUserId(HttpServletRequest request) throws GlobalRuntimeException{
        Object userInfo = request.getSession().getAttribute("user");
        if(userInfo != null) {
            User user = (User) userInfo;
            return user.getUserId();
        } else {
            return -1;
        }
    }
    /**
     * 获取用户id
     * @param request
     * @return
     */
    public int getTenantId(HttpServletRequest request) throws GlobalRuntimeException{
        Object userInfo = request.getSession().getAttribute("user");
        if(userInfo != null) {
            User user = (User) userInfo;
            return user.getTenantId();
        } else {
            return -1;
        }
    }
	
	@Override
	@Transactional
	public LogExecution insertLog(String moduleName, String content, HttpServletRequest request)  throws GlobalRuntimeException{
		LogExecution le = new LogExecution();
		try {
			int userId = -1;
			userId = getUserId(request);
			int tenantId = -1;
			tenantId = getTenantId(request);
			if(userId > 0) {
				Log log = new Log();
				log.setUserID(userId);
				log.setOperation(moduleName);
				log.setClientIP(Tools.getLocalIp(request));
				log.setCreateTime(new Date());
				log.setStatus(0);
				log.setContentDetails(content);
				log.setTenantId(tenantId);
				
				logMapper.insert(log);
				le.setState(LogStateEnum.SUCCESS.getState());
			}else {
				le.setState(LogStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			request.getSession().removeAttribute("user");
			throw new GlobalRuntimeException(e.getMessage());
		}
		return le;
	}
	@Override
	public LogExecution getLogList(Log log, int currentPage, int pageSize) {
		LogExecution le = new LogExecution();
		//查询条件
		QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
		//判断
		if(log.getOperation() != null && log.getOperation() != "") {
			queryWrapper.like("operation", log.getOperation());
		}
		if(log.getUserID() > 0) {
			queryWrapper.eq("userID", log.getUserID());
		}
		if(log.getClientIP() != null && log.getClientIP() != "") {
			queryWrapper.eq("clientIP", log.getClientIP());
		}
		if(log.getStatus() > 0) {
			queryWrapper.eq("status", log.getStatus());
		}
		if(log.getBeginTime() != null && log.getBeginTime() != "") {
			queryWrapper.ge("createTime", log.getBeginTime());
		}
		if(log.getEndTime() != null && log.getEndTime() != "") {
			queryWrapper.le("createTime", log.getEndTime());
		}
		if(log.getContentDetails() != null && log.getContentDetails() != "") {
			queryWrapper.like("contentDetails", log.getContentDetails());
		}
		queryWrapper.orderByDesc("logId");
		
		Page<Log> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = logMapper.selectMapsPage(page, queryWrapper);
		if(iPage.getRecords().size() > 0) {
			le.setState(LogStateEnum.SUCCESS.getState());
			le.setPages(page.getPages());//总页数
			le.setTotal(iPage.getTotal());//总记录数
			
			le.setLogPageList(iPage.getRecords());
		}else{
			le.setState(LogStateEnum.OFFLINE.getState());
		}
		
		return le;
	}

}
